#!/bin/bash
function build
{
    echo -e "Building $filename\n"
    encode "$1"
    pack "$1"
    if [ -x "/usr/share/epubcheck/lib/epubcheck.jar" ]
    then
    	 validate 
	 fi
    decode "$1"
}
function encode
{
    cd "$current/$1/Content"
    for x in *.xhtml
    do
        sed -i -f /usr/share/epub-builder/encode.sed "$x"
    done
}
function decode
{
    cd "$current/$1/Content"
    for x in *.xhtml
    do
        sed -i -f /usr/share/epub-builder/decode.sed "$x"
    done
}
function pack
{
    cd "$current/$1"
    zip -0Xq "$current"/"$filename" mimetype
    zip -Xr9Dq "$current"/"$filename" *
}
function validate
{
    cd $current
    java -jar /usr/share/epubcheck/lib/epubcheck.jar "$filename"
}

if [ "@$2" != "@" ]
then
    filename="$2.epub"
else
    filename="$1.epub"
fi
current=`pwd`
build "$1"
